layui.define(['table', 'treeTable', 'xmSelect', 'tableSelect', 'form', 'laydate'], function (exports) {

    var $ = layui.$
        , form = layui.form
        , table = layui.table
        , setter = layui.setter
        , admin = layui.admin
        , treeTable = layui.treeTable
        , tableSelect = layui.tableSelect
        , laydate = layui.laydate
        , xmSelect = layui.xmSelect

    var device = layui.device();
    if(device.os == 'windows'){//判断是电脑
    	$('style[mainStyle]').append('div,td,input,span,button,a,select,ul li,i,cite{font-size:14px!important;}');
	}else{//判断是平板
		if(window.screen.width > 1366){
			$('style[mainStyle]').append('div,td,input,span,button,a,select,ul li,i,cite{font-size:18px!important;}');
		}else{
			$('style[mainStyle]').append('div,td,input,span,button,a,select,ul li,i,cite{font-size:14px!important;}');
		}
	}
    var templatecode;
    var templatename;
    var parentJson = {};
 	var jobnumber = sessionStorage.getItem('jobnumber') == null?"":sessionStorage.getItem('jobnumber');
    var resdata=[];
    var saveJson = {};//保存更改过的数据
    var obj = {
        setParentJson: function setParentJson(json) {
            //parentJson = json;
            if(jobnumber != '' && jobnumber.length == 4){
            	$('input[name="whereshopcode"]').val(jobnumber);
            	$('input[name="whereshopcode"]').attr('readonly','readonly')
            }
            shopcode = parentJson.shopcode;
          //  templatecode = parentJson.templatecode;
            loadTime(shopcode)
        }

    }

//	------------------------------------------------------------------------------------------- 	

    function loadTime(shopcode) {
        colsArr = [
            {field: 'zizeng', title: '序号', align: 'center', fixed: 'left', templet: '#zizeng',width:"4%"},
            {field: 'gdsincode', fixed: 'left', title: '商品编码', align: 'center',width:"7%"},//goodscode
            {field: 'gdsname', title: '商品名称', align: 'center'},//goodsname
            {field: 'gdsclass', title: '商品ABC', align: 'center',width:"7%"},//goodsabc
            {field: 'status', title: '分店ABC', align: 'center',width:"7%"},//shopabc
            {field: 'shopcode', title: '门店编码', align: 'center', hide: true},//shopcode
            {field: 'sendstd', title: '配送规格', align: 'center',width:"7%"},//sendstd
            {field: 'storemaxstock', title: '现有上限', align: 'center',width:"7%"},//maxstock
            {field: 'storeminstock', title: '现有下限', align: 'center',width:"7%"},//minstock
            {field: 'dms', title: '日均销量', align: 'center',width:"7%"},//salenum
            {field: 'maxstock', title: '标准上限', align: 'center',width:"7%"},//basemaxstock
            {field: 'minstock', title: '标准下限', align: 'center',width:"7%"},//baseminstock
            {field: 'newmaxstock', title: '新参数上限', align: 'center', edit: 'text-tel',width:"8%"},//newmaxstock
            {field: 'newminstock', title: '新参数下限', align: 'center', edit: 'text-tel',width:"8%"},//newminstock   //Special
 			{field: 'Special', title: 'Special', align: 'center',width:"0%",hide: true},
			{field: 'nochange', title: 'nochange', align: 'center',width:"0%",hide: true}
        ]
        parentJson.Deptcode = "";
        parentJson.Gdsincode = "";
        parentJson.Gdsname= "";
        parentJson.Status = "A";
    	parentJson.current = "1";
        //商品
        table.render({
            elem: '#goods-table'
          //  , url: setter.host + '/yaohuo/canshuxiugai'
            , cols: [colsArr]
            , method: 'post'
            , contentType: 'application/json; charset=utf-8'
            //, where: parentJson
			,data:[]
        	,totalRow: true
            , page: true
            , limit: 15
            , limits: [15, 30, 50]
            , height: 'full-80'
            , text: {
                none: '暂无数据'
            }
            ,done:function(res, curr, count){ 
				console.log(res.data);
				resdata=res.data; 
				for(var i=0;i<resdata.length;i++){
					if(resdata[i].newmaxstock==undefined){resdata[i].oldmaxstock='';}else{resdata[i].oldmaxstock=resdata[i].newmaxstock;}
					if(resdata[i].newminstock==undefined){resdata[i].oldminstock='';}else{resdata[i].oldminstock=resdata[i].newminstock;}
					
				}
				console.log(res);
			}
        });
    	if($('input[name="whereshopcode"]').val() != ''){
        	$('button[lay-filter="LAY-genius-normal-search"]').trigger('click');
        }
    }

    $(document).on('keydown keyup', '.layui-input',
            function(event) {
                var td = $(this).parent('td'),
                    index = td.index(),
                    tr = td.parent('tr'),
                    isShift = $(document).data('shift'),
                    isKeydown = (event.type == "keydown");
                switch (event.key) {
                    case "Shift":
                        $(document).data('shift', isKeydown);
                        break;
                    case "Tab":
                        event.preventDefault();
                        isKeydown && td[isShift ? 'prev': 'next']().click();
                        break;
                    case "Enter":
						if(index=='12'){
							 index='13';
							 isKeydown && tr.children('td').eq(index).click();
						}else{
							 index='12'; 
						     isKeydown && tr[isShift ? 'prev': 'next']().children('td').eq(index).click();
						}
                       
                        break;
                    case "ArrowDown":
                        isKeydown && tr.next().children('td').eq(index).click();
                        break;
                    case "ArrowUp":
                        isKeydown && tr.prev().children('td').eq(index).click();
                        break;
                }
            })


    //监听锁定操作
    form.on('checkbox(autoDemo)', function (obj) {
        var elem = $(obj.elem);
        var trElem = elem.parents('tr');
        if (obj.elem.checked == true) {
            this.value = 0;
        } else {
            this.value = 1;
        }
        table.cache['goods-table'][trElem.data('index')]['isAuto'] = this.value;
    });
//----------------------------------------------------

    table.on('tool(goods-table)', function (obj) {
        var data = obj.data;

        if (obj.event === 'del') {
            layer.confirm('确认删除该行么', function (index) {

                obj.del();
                table.reload();
                layer.close(index);
            });
        }
    });


//	------------------------------------------------------------------------------------------- 	


    $('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    var active = {
        add: function () {
            dateType = 'add';
        }
    }

    table.on('edit(goods-table)', function (obj) {
        var value = Number(obj.value) //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field //得到字段
            , tr = obj.tr
       // var oldValue = $(tr).find("td[data-field='" + field + "'] div").text();
			, xvhao = obj.tr.selector.match(/\d+/g)[0];
		var oldValue ;
      	if(field == 'newmaxstock'){
	         oldValue = resdata[xvhao].oldmaxstock;
		}else{
			 oldValue = resdata[xvhao].oldminstock;
		}
		console.log(data);
        // console.log(oldValue)
        // //判断是否可调大
        // if (isNaN(value)) {
        //     layer.alert('数量必须填写数字');
        //     value = oldValue;
        //     $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
        // }
        if (field == 'newmaxstock') {
		   if (data.status == 'A' && data.Special == '1' && value == 0) {//data.allow0 != '0' && value == 0)
                layer.alert('上限不能调0');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if (data.status == '未定' && data.gdsclass == '未定' && data.Special == '1'  && value == 0) {//data.allowmax != '0' && value > oldValue
                layer.alert('上限不能调0');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if (data.status =='必卖品' && value < data.storemaxstock && value!='') {                  
                layer.alert('不可调低');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if(value < data.newminstock && data.newminstock!=''){
				layer.alert('上限必须大于下限');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} else if(!Number.isInteger(value)){
				layer.alert('必须为整数');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} else if(value<0||value>100){
				layer.alert('参数必须在0~100之间');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} else if(value!=0&&value<data.sendstd){
				layer.alert('非0上限不可小于配送规格');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} else if(data.nochange == '1' && value > data.storemaxstock){
				layer.alert('该商品的上限不可调高');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} 
		   data.newmaxstock = value;
        } else if (field == 'newminstock') {
			if (data.status == 'A' && data.Special == '1' && value == 0) {//data.allow0 != '0' && value == 0
                layer.alert('下限不能调0');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if (data.status == '未定' && data.gdsclass == '未定' && data.Special == '1'  && value == 0) {//data.allowmax != '0' && value > oldValue
                layer.alert('下限不能调0');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if (data.status =='必卖品' && value < data.storeminstock  && value!='') {
                layer.alert('不可调低');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
            } else if(value > data.newmaxstock){
				layer.alert('下限必须小于上限');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			}else if(!Number.isInteger(value)){
				layer.alert('必须为整数');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} else if(value<0||value>100){
				layer.alert('参数必须在0~100之间');
                value = oldValue;
                $(tr).find("td[data-field='" + field + "'] input").val(oldValue);
			} 
			data.newminstock = value;
        }
        saveJson[data.gdsincode] = data;
    })
//------------------------------------------------------
    $("#back").on("click", function () {
        bakUrl = setter.host + '/buhuo_param_shop/toSelect'
        window.location.href = bakUrl;
    })
//事件
    var active = {
        save: function () {
            var sendData = {};
//            var tempJson = {};
            //设置总的要货量和金额
//console.log(dataBak[0]);       
            sendData.Deptcode = $('input[name="whereshopcode"]').val();
            sendData.Login = jobnumber;
            sendData.Temptypeid = parentJson.Temletid;
//          sendData.temptype = parentJson.temletid;
            var goodsArray = [];
            
            //循环设置要货量和要货金额,分页使用
            for(var el in saveJson){
            	var goodsOne = {};
            	//goodsOne.TemplateTypeID = dataBak[i].TemplateTypeID1;
				goodsOne.Gdsincode=el;
				goodsOne.Newmax = saveJson[el].newmaxstock==undefined?"":saveJson[el].newmaxstock;
				goodsOne.Newmin = saveJson[el].newminstock==undefined?"":saveJson[el].newminstock;
				
            	goodsArray.push(goodsOne);
            	goodsOne = null;
            }
//            //循环设置要货量和要货金额
//            var dataBak = table.cache['goods-table'];  
//            for (var i = 0; i < dataBak.length; i++) {
//            	var goodsOne = {};
//            	//goodsOne.TemplateTypeID = dataBak[i].TemplateTypeID1;
//					goodsOne.Gdsincode=dataBak[i].gdsincode;
//					if(dataBak[i].newmaxstock==undefined){goodsOne.Newmax="";}else{goodsOne.Newmax=dataBak[i].newmaxstock;}
//					if(dataBak[i].newminstock==undefined){goodsOne.Newmin="";}else{goodsOne.Newmin=dataBak[i].newminstock;}
//            	goodsArray.push(goodsOne);
//            	goodsOne = null;
//            }
            var result = true;
            if(result){
            	sendData.Goods = goodsArray;
            	if (goodsArray.length == 0) {
            		layer.alert('数据错误!');
            	} else {
	                console.log(sendData);
            		var loading = layer.msg('正在保存中', {icon: 16, shade: 0.1, time:0});
            		layui.admin.req({
	        			url: setter.host + '/yaohuo/canshuxiugaiSave'
	        			, type: 'post'
	    				, dataType: 'json'
						, contentType: "application/json; charset=utf-8"
						, data: JSON.stringify(sendData)
						, done: function (res) {
							layer.close(loading);
							//请求成功后
							if (res.status == '1') {
								table.reload('goods-table');
								layer.msg(res.msg);
							} else {
								layer.msg(res.msg);
							}
						}
            		});
            	}
            }
//			layui.common.postUrl(sendData,setter.host+'/order_goodslist/editOrder');
        }
        , exportExcel: function () {
            parentJson.search = JSON.stringify(tableSearch);
            parentJson.format = "excel";
            parentJson.title = tableTitle;
            parentJson.field = tableField;
            layui.common.postUrl(parentJson, setter.host + '/order_goodslist/exportExcel');
        }
        , exportCsv: function () {
            parentJson.search = JSON.stringify(tableSearch);
            parentJson.format = "excel";
            parentJson.title = tableTitle;
            parentJson.field = tableField;
            layui.common.postUrl(parentJson, setter.host + '/order_goodslist/exportExcel');
        }
        , exportPdf: function () {
            layer.msg('暂不支持');
        }
        , exportWord: function () {
            layer.msg('暂不支持');
        }
    };


	//监听搜索
	form.on('submit(LAY-genius-normal-search)', function(data){
		if(data.field.whereshopcode != ''){
		  	parentJson.Deptcode = data.field.whereshopcode;
		}else{
			return layer.msg('门店编码不能为空');
		}
		if(data.field.wheregdsname != ''){
			 parentJson.Gdsname= data.field.wheregdsname;
		}else{
			parentJson.Gdsname="";
		}	
		if(data.field.wheregdscode != ''){
			 parentJson.Gdsincode= data.field.wheregdscode;
		}else{
			parentJson.Gdsincode = "";
		}
		if(data.field.wherestatus != ''){
			 parentJson.Status= data.field.wherestatus;
		}else{
			parentJson.Status = "";
		}	
		//执行重载
		table.reload('goods-table', {
		
			where: parentJson
			, url: setter.host + '/yaohuo/canshuxiugai'
		});
	});
	
	
    exports('insert', obj);
});
//---------------------------------------------------------------------------
//roleTable = table.render({
//elem: '#LAY-role-list1'
//,url:'/unite_platform/goods_class/getclasslabel'
//,cols: [[
//{type:'checkbox'}
//,{field:'id', width:80, title: 'ID', sort: true}
//,{field:'name', width:80, title: '用户名'}
//]]
//,page: true
//});



